<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :visible.sync="visible"
    :show-close="false">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="120px">
      <el-form-item label="分类名称" prop="name">
        <el-input v-model="dataForm.name" placeholder="请填写分类名称" :maxlength="20"></el-input>
      </el-form-item>
      <el-form-item label="关键字" prop="keywords">
        <el-input v-model="dataForm.keywords" placeholder="请填写关键字" :maxlength="20"></el-input>
      </el-form-item>
      <el-form-item label="描述" prop="frontDesc">
        <el-input v-model="dataForm.frontDesc" placeholder="请填写描述" type="textarea" :rows="2" :maxlength="100"></el-input>
      </el-form-item>
      <el-form-item label="级别" size="mini" prop="level">
        <el-radio-group v-model="dataForm.level">
          <el-radio :label="'L1'">L1</el-radio>
          <el-radio :label="'L2'">L2</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="父节点" size="mini" prop="parentId" v-if="dataForm.level=='L2'">
        <el-select v-model="dataForm.parentId" placeholder="请选择" size="medium">
          <el-option
            v-for="item in parentCategory"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="排序" size="mini" prop="sortOrder">
        <el-input-number v-model="dataForm.sortOrder" :min="1" label="排序" size="medium"></el-input-number>
      </el-form-item>
      <el-form-item label="首页展示排序" size="mini" prop="showIndex">
        <el-input-number v-model="dataForm.showIndex" :min="1" label="排序" size="medium"></el-input-number>
      </el-form-item>
      <el-form-item label="显示" size="mini" prop="isShow">
        <el-radio-group v-model="dataForm.isShow">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="frontName" prop="frontName">
        <el-input v-model="dataForm.frontName" placeholder="frontName" type="textarea" :rows="2" :maxlength="100"></el-input>
      </el-form-item>
      <el-row type="flex" justify="space-between">
        <el-col :span="12">
          <el-form-item label="banner图片" size="mini" prop="bannerUrl">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="bannerUrlOnSuccess"
              :before-upload="beforeUploadHandle">
              <img v-if="dataForm.bannerUrl" :src="dataForm.bannerUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="icon链接" size="mini" prop="iconUrl">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="iconUrlOnSuccess"
              :before-upload="beforeUploadHandle">
              <img v-if="dataForm.iconUrl" :src="dataForm.iconUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row type="flex" justify="space-between">
        <el-col :span="12">
          <el-form-item label="图片" size="mini" prop="imgUrl">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="imgUrlOnSuccess"
              :before-upload="beforeUploadHandle">
              <img v-if="dataForm.imgUrl" :src="dataForm.imgUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机banner" size="mini" prop="wapBannerUrl">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="wapBannerUrlOnSuccess"
              :before-upload="beforeUploadHandle">
              <img v-if="dataForm.wapBannerUrl" :src="dataForm.wapBannerUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="cancelHandle()">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        visible: false,
        uploadUrl: '',
        deleteUrl: '',
        parentCategory: [],
        oldImgUrl: [],
        newImgUrl: [],
        dataForm: {
          id: 0,
          name: '',
          keywords: '',
          frontDesc: '',
          parentId: '',
          sortOrder: 1,
          showIndex: 1,
          isShow: 1,
          bannerUrl: '',
          iconUrl: '',
          imgUrl: '',
          wapBannerUrl: '',
          level: 'L1',
          type: '',
          frontName: ''
        },
        dataRule: {
          name: [
            { required: true, message: '分类名称不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    created () {
      this.uploadUrl = this.$http.adornUrl(`/back/file/upload?token=${this.$cookie.get('token')}`)
      this.deleteUrl = this.$http.adornUrl('/back/file/deleteByUrl')
    },
    methods: {
      init (id) {
        this.dataForm.id = id || 0
        this.oldImgUrl = []
        this.newImgUrl = []
        this.$http({
          url: this.$http.adornUrl('/back/category/select'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          this.parentCategory = data.data
        }).then(() => {
          this.visible = true
          this.$nextTick(() => {
            this.$refs['dataForm'].resetFields()
          })
        }).then(() => {
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/back/category/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.name = data.data.name
                this.dataForm.keywords = data.data.keywords
                this.dataForm.frontDesc = data.data.frontDesc
                this.dataForm.parentId = data.data.parentId
                this.dataForm.sortOrder = data.data.sortOrder
                this.dataForm.showIndex = data.data.showIndex
                this.dataForm.isShow = data.data.isShow
                this.dataForm.level = data.data.level
                this.dataForm.type = data.data.type
                this.dataForm.frontName = data.data.frontName
                this.dataForm.bannerUrl = data.data.bannerUrl
                this.dataForm.iconUrl = data.data.iconUrl
                this.dataForm.imgUrl = data.data.imgUrl
                this.dataForm.wapBannerUrl = data.data.wapBannerUrl
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      /**
       *表单提交
       * */
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/back/category/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'name': this.dataForm.name,
                'keywords': this.dataForm.keywords,
                'frontDesc': this.dataForm.frontDesc,
                'parentId': this.dataForm.level === 'L2' ? this.dataForm.parentId : 0,
                'sortOrder': this.dataForm.sortOrder,
                'showIndex': this.dataForm.showIndex,
                'isShow': this.dataForm.isShow,
                'level': this.dataForm.level,
                'type': this.dataForm.type,
                'frontName': this.dataForm.frontName,
                'bannerUrl': this.dataForm.bannerUrl,
                'iconUrl': this.dataForm.iconUrl,
                'imgUrl': this.dataForm.imgUrl,
                'wapBannerUrl': this.dataForm.wapBannerUrl
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                for (let i in this.oldImgUrl) {
                  this.handleRemove(this.oldImgUrl[i])
                }
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      /**
       *图片上传之前的钩子
       * */
      beforeUploadHandle (file) {
        if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
          this.$message.error('只支持jpg、png、gif格式的图片！')
          return false
        }
      },
      /**
       *取消事件
       * */
      cancelHandle () {
        if (!this.dataForm.id) {
          for (let i in this.oldImgUrl) {
            this.handleRemove(this.oldImgUrl[i])
          }
        }
        for (let i in this.newImgUrl) {
          this.handleRemove(this.newImgUrl[i])
        }
        this.visible = false
      },
      /**
       *删除图片
       * */
      handleRemove (oldUrl) {
        if (oldUrl) {
          this.$http({
            url: this.deleteUrl,
            method: 'post',
            data: oldUrl
          })
        }
      },
      /**
       *bannerUrl图片上传成功后的钩子
       * */
      bannerUrlOnSuccess (response, file, fileList) {
        let oldUrl = this.dataForm.bannerUrl
        if (response && response.code === 0) {
          this.dataForm.bannerUrl = response.url
          this.newImgUrl.push(response.url)
          if (oldUrl) {
            this.oldImgUrl.push(oldUrl)
          }
        } else {
          this.$message.error(response.msg)
        }
      },
      /**
       *iconUrl图片上传成功后的钩子
       * */
      iconUrlOnSuccess (response, file, fileList) {
        let oldUrl = this.dataForm.iconUrl
        if (response && response.code === 0) {
          this.dataForm.iconUrl = response.url
          this.newImgUrl.push(response.url)
          if (oldUrl) {
            this.oldImgUrl.push(oldUrl)
          }
        } else {
          this.$message.error(response.msg)
        }
      },
      /**
       *imgUrl图片上传成功后的钩子
       * */
      imgUrlOnSuccess (response, file, fileList) {
        let oldUrl = this.dataForm.imgUrl
        if (response && response.code === 0) {
          this.dataForm.imgUrl = response.url
          this.newImgUrl.push(response.url)
          if (oldUrl) {
            this.oldImgUrl.push(oldUrl)
          }
        } else {
          this.$message.error(response.msg)
        }
      },
      /**
       *wapBannerUrl图片上传成功后的钩子
       * */
      wapBannerUrlOnSuccess (response, file, fileList) {
        let oldUrl = this.dataForm.wapBannerUrl
        if (response && response.code === 0) {
          this.dataForm.wapBannerUrl = response.url
          this.newImgUrl.push(response.url)
          if (oldUrl) {
            this.oldImgUrl.push(oldUrl)
          }
        } else {
          this.$message.error(response.msg)
        }
      }
    }
  }
</script>

<style lang="scss">
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
